package com.my.socket.nio.v1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created by ZhongGang
 * at 2018/6/27 17:25
 */
public class ReverseServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReverseServer.class);

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 9999), Integer.MAX_VALUE);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            LOGGER.info("waiting for something happen...");
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                try {
                    if (next.isAcceptable()) {
                        ServerSocketChannel selectableChannel = (ServerSocketChannel) next.channel();
                        SocketChannel socketChannel = selectableChannel.accept();
                        LOGGER.info("connection coming: {}", socketChannel);
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (next.isReadable()) {
                        SocketChannel selectableChannel = (SocketChannel) next.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int length;
                        while ((length = selectableChannel.read(byteBuffer)) > 0) {
                            byteBuffer.flip();
                            String request = new String(byteBuffer.array(), 0, length);
                            byteBuffer.clear();
                            LOGGER.info("reading: {}, length: {}", request, request.length());
                        }
                    } else if (next.isWritable()) {
                        SocketChannel selectableChannel = (SocketChannel) next.channel();
                        LOGGER.info("writing: {}");
                    }
                } catch (Exception e) {
                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                } finally {
                    iterator.remove();
                }
            }
        }
    }
}
